package com.sl.common.trans;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.fhs.trans.service.impl.DictionaryTransService;
import com.fhs.trans.service.impl.RpcTransService;
import com.fhs.trans.service.impl.SimpleTransService;
import com.sl.common.enums.DictionaryEnum;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Configuration
public class TranServiceConfig implements BeanPostProcessor {


    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof RpcTransService) {
            return bean;
        }
        if (bean instanceof SimpleTransService) {
            SimpleTransService service = (SimpleTransService) bean;
            CustomSimpleTransService customSimpleTransService = new CustomSimpleTransService(service);
//
            return customSimpleTransService;
        }
        return bean;
    }


    @Bean
    public ApplicationRunner applicationRunner(){
        return (args)->{

            DictionaryTransService bean = SpringUtil.getBean(DictionaryTransService.class);

            Set<Class<?>> classes = ClassUtil.scanPackageBySuper("com.byj.pms", DictionaryEnum.class);

            for (Class<?> s : classes) {
                if (!s.isEnum()) {
                    continue;
                }
//            Class<Enum> objectClass = ClassUtil.loadClass(s);
                Map<String, Enum> enumMap = EnumUtil.getEnumMap((Class<Enum>) s);

                Map<String, String> transMap = new HashMap<>();
                for (Map.Entry<String, Enum> stringEnumEntry : enumMap.entrySet()) {
                    String key = stringEnumEntry.getKey();
                    Enum value = stringEnumEntry.getValue();
                    if (value instanceof DictionaryEnum val) {
                        String key1 = val.getKey();
                        String value1 = val.getValue();
                        String desc = val.getDesc();
                        transMap.put(value1, desc);
                    }
                }
                if (MapUtil.isNotEmpty(transMap)) {
                    bean.refreshCache(s.getSimpleName(), transMap);
                }
            }
        };
    }
}
